<template>
  <div class="container">
    <h1 class="title">基金公司列表</h1>

    <!-- 筛选区域 -->
    <el-row class="filters" gutter="12" align="middle">
      <el-col :xs="24" :sm="8">
        <el-select
            v-model="selectedTags"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择标签"
            clearable
            style="width: 100%"
        >
          <el-option
              v-for="tag in tags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.name"
          />
        </el-select>
      </el-col>
      <el-col :xs="24" :sm="8">
        <el-input
            v-model="keyword"
            placeholder="输入基金公司名称"
            clearable
            style="width: 100%"
        />
      </el-col>
      <el-col :xs="12" :sm="4">
        <el-button type="primary" @click="searchCompanies" style="width: 100%">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :xs="12" :sm="4">
        <el-button @click="resetFilters" style="width: 100%">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-col>
    </el-row>

    <p style="margin-top: 12px;">共 {{ total }} 家基金公司</p>

    <el-alert
        v-if="selectedFunds.length > 0"
        type="info"
        show-icon
        :title="`已选中 ${selectedFunds.length} 只基金`"
        style="margin-bottom: 12px;"
    />

    <el-table
        :data="companies"
        border
        row-key="id"
        style="width: 100%"
        :expand-row-keys="expandedRows"
        @expand-change="loadCompanyFunds"
    >
      <el-table-column type="expand">
        <template #default="props">
          <el-table
              :ref="el => fundTableRefs[props.row.id] = el"
              :data="props.row.funds || []"
              size="small"
              border
              :row-key="fund => fund.code"
              @selection-change="selection => handleSelectionChange(selection, props.row)"
              @row-click="(row) => toggleRowSelection(row, props.row)"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="code" label="基金代码" width="120" />
            <el-table-column prop="name" label="基金名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="managerName" label="基金经理" />
            <el-table-column prop="latestNav" label="最新净值" />
            <el-table-column prop="latestNavDate" label="净值日期" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                    size="small"
                    type="success"
                    plain
                    @click.stop="viewProfile(scope.row)"
                >
                  查看画像
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="基金公司" width="200" />
      <el-table-column prop="shortName" label="简称" />
      <el-table-column prop="rating" label="评级" />
      <el-table-column prop="fundCount" label="管理基金数" />
    </el-table>

    <!-- 分页与操作 -->
    <div style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center;">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />

      <el-button
          type="success"
          :disabled="selectedFunds.length === 0"
          @click="dialogVisible = true"
      >
        <el-icon><FolderAdd /></el-icon>
        保存为组合
      </el-button>
    </div>

    <!-- 保存组合弹窗复用封装 -->
    <SavePortfolioDialog
        v-model="dialogVisible"
        :fund-codes="selectedFunds"
        :user-id="1"
        @saved="fetchCompanies"
    />

    <!-- 基金画像弹窗复用封装 -->
    <FundProfileDialog
        v-model="profileDialogVisible"
        :profile-data="dialogFundProfile"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search, Refresh, FolderAdd } from '@element-plus/icons-vue'

import SavePortfolioDialog from '@/components/SavePortfolioDialog.vue'
import FundProfileDialog from '@/components/FundProfileDialog.vue'

const companies = ref([])
const tags = ref([])
const selectedTags = ref([])
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const expandedRows = ref([])

const selectedFunds = ref([])
const fundTableRefs = ref({})
const companySelections = ref({})

const dialogVisible = ref(false)
const profileDialogVisible = ref(false)
const dialogFundProfile = ref(null)

onMounted(() => {
  loadTags()
  fetchCompanies()
})

const loadTags = async () => {
  const res = await axios.get('/api/tag/all')
  tags.value = res.data
}

const fetchCompanies = async () => {
  if (selectedTags.value.length > 0) {
    const res = await axios.get('/api/fund-company/by-tags', {
      params: { tags: selectedTags.value },
      paramsSerializer: params => {
        const searchParams = new URLSearchParams()
        for (const key in params) {
          const value = params[key]
          if (Array.isArray(value)) {
            value.forEach(v => searchParams.append(key, v))
          } else if (value !== null && value !== undefined) {
            searchParams.append(key, value)
          }
        }
        return searchParams.toString()
      }
    })
    companies.value = res.data
    total.value = res.data.length
  } else {
    const res = await axios.get('/api/fund-company/page', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value,
        keyword: keyword.value
      }
    })
    companies.value = res.data.content
    total.value = res.data.totalElements
  }
  expandedRows.value = []
}

const loadCompanyFunds = async (row, expanded) => {
  if (expanded && !row.funds) {
    const res = await axios.get('/api/fund-company/funds', {
      params: { companyName: row.name }
    })
    row.funds = res.data
    await nextTick()
    const tableRef = fundTableRefs.value[row.id]
    if (tableRef && row.funds) {
      row.funds.forEach(fund => {
        if (selectedFunds.value.includes(fund.code)) {
          tableRef.toggleRowSelection(fund, true)
        }
      })
    }
  }
}

const toggleRowSelection = (row, companyRow) => {
  const tableRef = fundTableRefs.value[companyRow.id]
  if (tableRef) {
    tableRef.toggleRowSelection(row)
  }
}

const handleSelectionChange = (selection, companyRow) => {
  companySelections.value[companyRow.id] = selection.map(f => f.code)
  const allSelected = Object.values(companySelections.value).flat()
  selectedFunds.value = Array.from(new Set(allSelected))
}

const searchCompanies = () => {
  currentPage.value = 1
  fetchCompanies()
}

const resetFilters = () => {
  keyword.value = ''
  selectedTags.value = []
  currentPage.value = 1
  fetchCompanies()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCompanies()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchCompanies()
}

const viewProfile = async (row) => {
  try {
    const res = await axios.get(`/api/fund-profile/${row.code}`)
    dialogFundProfile.value = res.data
    profileDialogVisible.value = true
  } catch (err) {
    ElMessage.error('加载画像失败：' + (err.response?.data?.message || err.message))
  }
}
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px;
}
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
}
.filters {
  margin-bottom: 16px;
}
</style>
